package com.glodon.paas.search.resource;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.glodon.paas.search.listener.IndexListener;
import com.glodon.paas.search.model.DatabagEvent;
import com.glodon.paas.search.model.EventType;
import com.glodon.paas.search.model.HitFiles;
import com.glodon.paas.search.model.IndexRevitStructure;
import com.glodon.paas.search.model.QueryRevitStructure;
import com.glodon.paas.search.query.QueryService;
import com.glodon.paas.search.util.SearchConstants;
import com.sun.jersey.api.core.InjectParam;

@Component
@Path("/internal/bag")
public class DatabagResource {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    @Qualifier("databagListener")
    private IndexListener listener;

    @Autowired
    @Qualifier("revitQueryService")
    private QueryService<IndexRevitStructure, QueryRevitStructure> revitQueryService;

    /**
     * 数据包完成时收到到通知
     * 
     * @param databagId
     * @return
     */
    @PUT
    @Path("/{databagId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response onFinished(@PathParam("databagId") String databagId) {
        logger.info("received databag notify, databagId:{}", databagId);
        DatabagEvent event = new DatabagEvent(databagId, EventType.UPLOAD);
        listener.onEvent(event);
        return Response.ok("{\"result\":\"success\"}").build();
    }

    @DELETE
    @Path("/{databagId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response onDelete(@PathParam("databagId") String databagId) {
        DatabagEvent event = new DatabagEvent(databagId, EventType.DELETE);
        listener.onEvent(event);
        return Response.ok("{\"result\":\"success\"}").build();
    }

    @GET
    @Path("/rvt")
    public Response searchRvt(@InjectParam QueryRevitStructure file) {
        logger.debug("received revit search:{}", file);
        HitFiles<IndexRevitStructure> hitFiles = revitQueryService.query(SearchConstants.INDEX_PAAS,
                SearchConstants.TYPE_RVT, file);
        return Response.ok(hitFiles, MediaType.APPLICATION_JSON).build();
    }
}
